package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OrderReceiver {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //监听消息
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel) {
        //判断当前的订单不为空
        try {
            if (orderId != null) {
                //  发过来的是订单Id，那么你就需要判断一下当前的订单是否已经支付了。
                //  未支付的情况下：关闭订单
                //  根据订单Id 查询orderInfo select * from order_info where id = orderId
                //  利用这个接口IService  实现类ServiceImpl 完成根据订单Id 查询订单信息 ServiceImpl 类底层还是使用的mapper
                //            OrderInfo orderInfo = orderService.getById(orderId);
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null
                        && "UNPAID".equals(orderInfo.getOrderStatus())
                        && "UNPAID".equals(orderInfo.getProcessStatus())) {
                    //判断是否有本地交易记录
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    if (paymentInfo != null && "UNPAID".equals(paymentInfo.getPaymentStatus())) {
                        //orderInfo + paymentInfo
                        orderService.cancelOrder(orderId, "2");

                        //判断是否有交易记录产生
                        Boolean result = this.paymentFeignClient.checkPayment(orderId);
                        if (result) {
                            //需要关闭支付宝交易记录
                            Boolean flag = this.paymentFeignClient.closePay(orderId);
                            if (flag) {//true 说明有交易记录 但未支付
                                    //  false: 没有交易记录只关闭 orderInfo + paymentInfo
                                orderService.cancelOrder(orderId, "2");
                            } else {
                                //false：说明关闭失败！在即将关闭那一瞬间  付款了
                            }
                        }else{
                            //  false: 没有交易记录只关闭 orderInfo + paymentInfo
                            orderService.cancelOrder(orderId,"2");
                        }

                    } else {
                        //如若未支付等于订单状态和进程状态 那么就取消订单 只需要关闭orderInfo
                        orderService.cancelOrder(orderId, "1");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  手动确认消息 如果不确认，有可能会到消息残留。
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //监听更新订单状态消息
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId, Message message, Channel channel) {
        try {
            //判断订单id
            if (orderId != null) {
                //修改订单状态
                orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                //发送消息给库存
                orderService.sendOrderStatus(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //手动确认消息  false 不批量确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void wareOrder(String strJson, Message message, Channel channel) {
        try {
            //  判断
            if (!StringUtils.isEmpty(strJson)) {
                //  需要将strJson 这个Json数据转换为java 能操作的对象！
                Map map = JSON.parseObject(strJson, Map.class);
                //  获取map 中的数据！
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  判断状态
                if ("DEDUCTED".equals(status)) {
                    //  说明减库存成功！ 等待发货
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);
                } else {
                    //  说明减库存失败！
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.STOCK_EXCEPTION);
                    //  1.  库存不足，则需要调用其他仓库的货物！  2.  亲，不好意思......
                }
            }
        } catch (NumberFormatException e) {
            //  记录订单Id ，写入哪条失败！
            e.printStackTrace();
        }

        //  手动确认消息！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }
}
